// 引入 react 依赖
import React, { Component } from 'react';
import { Provider, connect } from 'react-redux';

import { StyleSheet, TextInput, Text, ScrollView, View, Platform, NativeModules, StatusBar, TouchableOpacity } from 'react-native';
const { StatusBarManager } = NativeModules;

import { Scene, Router, Actions, Reducer, ActionConst, Overlay, Tabs, Modal, Drawer, Stack, Lightbox } from 'react-native-router-flux';

// 引入 redux 所需文件
import store from './src/store/store.js'

// 引入第三方依赖
// import _ from 'lodash';
import pureRender from 'pure-render-decorator';
import SplashScreen from 'react-native-splash-screen'
import * as ActionTypes from './src/constants/constants.js';
import * as AntDesign from '@ant-design/react-native';
import AliyunPush from 'react-native-aliyun-push';

// 引入组件
import {
  Advertise,
  Login,
  Home,
  Exchange,
  PositionDetails,
  User,
  ResetPassword,
  VerifyPhone,
  PositionHistory,
  Binding,
  UserInfo,
  AccessFirmOffer,
  Setting,
  UpdataUser,
} from './src/router/index.js'; //引入文件
import { TabBar } from './src/components/index.js'; //引入文件
// [RNSplashScreen show];
import { AppId, ScreenWidth, ScreenHeight, loadData } from './src/util/utils.js'


// 修改defaultProps 设置allowFontScaling = false
TextInput.defaultProps = Object.assign({}, TextInput.defaultProps, { defaultProps: false })
Text.defaultProps = Object.assign({}, Text.defaultProps, { allowFontScaling: false })
ScrollView.defaultProps = Object.assign({}, ScrollView.defaultProps, { showsVerticalScrollIndicator: false })
TouchableOpacity.defaultProps = Object.assign({}, TouchableOpacity.defaultProps, { activeOpacity: .9 })

export default class App extends Component {

  constructor(props) {
    super(props)
    this.state = {
    }
  }

  componentDidMount() {
    SplashScreen.hide()
    if (Platform.OS == 'ios') {
      StatusBarManager.getHeight(statusBarHeight => {
        store.dispatch({
          type: ActionTypes.setStatusHeight,
          data: statusBarHeight.height
        })
      })
    } else {
      store.dispatch({
        type: ActionTypes.setStatusHeight,
        data: StatusBar.currentHeight
      })
    }
    //监听推送事件
    AliyunPush.addListener(this.handleAliyunPushMessage);
    AliyunPush.getDeviceId().then((deviceId) => {
      console.log("deviceId:" + deviceId);
    }).catch((error) => {
      console.log(error);
      console.log("getDeviceId() failed");
    });
  }

  async componentWillUnmount() {
    //移除监听
    AliyunPush.removeListener(this.handleAliyunPushMessage);

    //也可以用移除全部监听
    // AliyunPush.removeAllListeners()
    const msg = await AliyunPush.getInitialMessage();
    if (msg) {
      this.handleAliyunPushMessage(msg);
    }


  }

  handleAliyunPushMessage = (e) => {
    console.log(e);
    console.log(e.extras)
    console.log(e.actionIdentifier)
    if (e.actionIdentifier && e.actionIdentifier == 'opened') {
      const { userId, id, exchangeId } = e.extras
      console.log(userId, id)
      Actions.positionDetails({ exchangeId, id, userId })
    }
    // Actions.positionDetails({ id, userId })
    //e结构说明:
    //e.type: "notification":通知 或者 "message":消息
    //e.title: 推送通知/消息标题
    //e.body: 推送通知/消息具体内容
    //e.actionIdentifier: "opened":用户点击了通知, "removed"用户删除了通知, 其他非空值:用户点击了自定义action（仅限ios）
    //e.extras: 用户附加的{key:value}的对象
  };


  render() {
    const onBackPress = () => {
      if (Actions.state.index !== 0) {
        return false
      }
      Actions.pop()
      return true
    }
    const prefix = Platform.OS === 'android' ? 'mychat://mychat/' : 'mychat://';

    const stateHandler = (prevState, newState, action) => {
      // console.log('onStateChange: ACTION:', action);
    };

    const normalNav = { navigationBarStyle: { backgroundColor: '#EB4B6E', borderBottomWidth: 0, elevation: 0 }, titleStyle: { color: '#fff' } }
    return (
      <AntDesign.Provider>
        <Provider store={store}>
          {/* <SimpleApp /> */}
          {/* <Router backAndroidHandler={onBackPress} > */}
          <Router onStateChange={stateHandler} uriPrefix={prefix}>
            <Overlay key="overlay">
              <Modal key="modal" hideNavBar >
                <Scene key="advertise" initial title="广告" component={Advertise} hideNavBar={true} {...normalNav} />
                <Lightbox key="lightbox">
                  <Stack key="root" titleStyle={{ alignSelf: 'center' }} hideNavBar >
                    <Tabs
                      key="tabBar"        // 唯一标识
                      wrap={true}         // 自动使用自己的导航栏包装每个场景
                      showLabel={false}   // 显示文字
                      tabBarStyle={styles.tabbarContaine} // tabBar的样式
                      swipeEnabled={false}// 是否可以滑动
                      headerMode='screen' // 页面切换方式
                      icon={TabBar}      // 自定义Icon显示方式
                      lazy={true}         // 是否默认渲染tabbar
                      tabBarPosition={'bottom'}       // tabbar在顶部还是底部，iOS默认顶部，安卓默认顶部
                      tabBarOnPress={(e) => {
                        Actions[e.navigation.state.key]()
                      }}
                    >
                      <Scene key="exchange" navTransparent={true} title="实盘" component={Exchange} hideNavBar={true} sceneKey="exchange"  {...normalNav} />
                      <Scene key="user" navTransparent={true} title="个人中心" component={User} hideNavBar={true} sceneKey="user" {...normalNav} />
                    </Tabs>
                  </Stack>
                </Lightbox>
                <Scene key="login" navTransparent={true} title="登录" component={Login} hideNavBar={true} {...normalNav} />
                <Scene key="positionDetails" navTransparent={true} title="持仓详情" component={PositionDetails} hideNavBar={true} {...normalNav} />
                <Scene key="resetPassword" navTransparent={true} title="重置密码" component={ResetPassword} hideNavBar={true} {...normalNav} />
                <Scene key="verifyPhone" navTransparent={true} title="验证手机" component={VerifyPhone} hideNavBar={true} {...normalNav} />
                <Scene key="positionHistory" navTransparent={true} title="持仓历史" component={PositionHistory} hideNavBar={true} {...normalNav} />
                <Scene key="binding" navTransparent={true} title="绑定公众号" component={Binding} hideNavBar={true} {...normalNav} />
                <Scene key="userInfo" navTransparent={true} title="个人中心" component={UserInfo} hideNavBar={true} {...normalNav} />
                <Scene key="accessFirmOffer" navTransparent={true} title="接入实盘" component={AccessFirmOffer} hideNavBar={true} {...normalNav} />
                <Scene key="setting" navTransparent={true} title="设置" component={Setting} hideNavBar={true} {...normalNav} />
                <Scene key="updataUser" navTransparent={true} title="修改信息" component={UpdataUser} hideNavBar={true} {...normalNav} />
              </Modal>
            </Overlay>
          </Router>
        </Provider>
      </AntDesign.Provider>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
  tabbarContaine: {
    borderTopColor: '#0A0C21',
    backgroundColor: '#181E3A'
  }
});
